/*  This file is part of Phantom Power.
 *  Copyright (C) 2010 Jacob Dawid
 *
 *  Phantom Power is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Phantom Power is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Phantom Power. If not, see <http://www.gnu.org/licenses/>.
 */

#include "connection.h"
#include <iostream>

connection::connection()
{	
	settings=new QSettings("phantom-power.configuration", QSettings::IniFormat);
	connectionStateMutex=new QMutex();	
	setConnectionState(false);
}

connection::~connection()
{
	stop();
	delete connectionStateMutex;
	delete settings;
}

bool connection::start(int ip1, int ip2, int ip3, int ip4, int port)
{
	thisType=connection::wifi;
	socket=new QTcpSocket(this);	
	connect(socket, SIGNAL(readyRead()), this, SLOT(readSlot()));

	if(!socket)
		return false;

	connect(socket, SIGNAL(hostFound()), this, SLOT(hostFoundSlot()));
	connect(socket, SIGNAL(connected()), this, SLOT(connectedSlot()));
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)));
	connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));	
	
	QString ipAddress=QString("%1.%2.%3.%4").arg(ip1).arg(ip2).arg(ip3).arg(ip4);
	emit report("Now connecting to "+ipAddress+":"+QString("%1").arg(port));
	socket->connectToHost(ipAddress, port);
	return true;
}
		
bool connection::stop()
{
	emit report("Now disconnecting.");
	socket->disconnectFromHost();
	return true;
}

bool connection::connectionState()
{
	bool value;
	connectionStateMutex->lock();
	value=_connectionState;
	connectionStateMutex->unlock();
	return value;
}

void connection::hostFoundSlot()
{
	emit report("Host found.");
}

void connection::connectedSlot()
{
	emit report("Connection established.");
	setConnectionState(true);
}

void connection::errorSlot(QAbstractSocket::SocketError socketError)
{
	emit report("An error occured: "+socket->errorString());
}

void connection::disconnectedSlot()
{
	emit report("Disconnected.");
	setConnectionState(false);
}

void connection::readSlot()
{
	if(!connectionState())
		return;

	QByteArray byteArray=socket->readAll();
	QString data(byteArray);
	
	if(data.contains("<"))
	{
		emit controlSignal(data);	
		return;	
	}
	
	QStringList issues=data.split("]");
	int i;
	
	for(i=0;i<issues.count();i++)
		if(issues[i].length()>5)
		{
			QList<double> decodedIssue=decodeIssue(issues[i]);
				emit issueAvailable(decodedIssue);
		}
}

void connection::synchronize()
{
	settings->sync();
}

QList<double> connection::decodeIssue(QString issue)
{
	QList<double> decodedIssue;
	QRegExp regularExpression("\\[|\\{|\\}|;|,");
	QStringList list=issue.split(regularExpression, QString::SkipEmptyParts);
	
	for(int i=0;i<list.count();i++)
		decodedIssue.append(list[i].toDouble());
	return decodedIssue;	
}

void connection::setConnectionState(bool value)
{
	connectionStateMutex->lock();
	_connectionState=value;
	connectionStateMutex->unlock();
}
		
